package com.unsins.restlet;

import com.unsins.business.domain.system.ISysConstantRepository;
import com.unsins.business.domain.system.SysConstant;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.data.*;
import org.restlet.resource.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: odpsoft
 * Date: 2008-11-27
 * Time: 16:18:42
 */
public class SysConstantsResource extends Resource {
    private static final Logger logger = Logger.getLogger(SysConstantResource.class.getName());
    private ISysConstantRepository constantRepository;
    private String typeCode;
    private List<SysConstant> constantArray;

    public void setSysConstantRepository(ISysConstantRepository repository) {
        constantRepository = repository;
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        typeCode = (String) request.getAttributes().get("typecode");
        constantArray = null;
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public Representation represent(Variant variant) throws ResourceException {
        logger.info("start done sysconstant restlet!");
        Map<String, String> keyMap = new HashMap<String, String>();
        keyMap.put("typeCode", typeCode);
        constantArray = constantRepository.findAllByMapKey(SysConstant.class, keyMap);
        JSONArray array = new JSONArray();

        try {
            for (SysConstant sysConstant : constantArray) {
                JSONObject json = new JSONObject();

                json.put("name", sysConstant.getListName());
                json.put("code", sysConstant.getListCode());
                json.put("id", sysConstant.getId());

                array.put(json);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return new StringRepresentation(array.toString(), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
    }
}
